package com.capgemini.simpleappblanche.controller.customer.validator;

import org.springframework.util.StringUtils;
import org.springframework.validation.Errors;
import org.springframework.validation.Validator;

import com.capgemini.simpleappblanche.constant.ValidatorConstant;
import com.capgemini.simpleappblanche.domain.constant.CustomerConstant;
import com.capgemini.simpleappblanche.dto.CustomerDto;

public class CustomerDtoValidator implements Validator {

	/**
     * {@inheritDoc}
     * @see org.springframework.validation.Validator#supports(java.lang.Class)
     */
    @Override
    public boolean supports(Class<?> clazz) {
        return CustomerDto.class.isAssignableFrom(clazz);
    }

	/**
	 * {@inheritDoc}
	 * @see org.springframework.validation.Validator#validate(java.lang.Object, org.springframework.validation.Errors)
	 */
	@Override
    public void validate(Object target, Errors errors) {
		CustomerDto form = (CustomerDto) target;
        
        // checks name
        if (!StringUtils.hasText(form.getName())) {
            errors.rejectValue("name", ValidatorConstant.KEY_REQUIRED, 
            		new Object[] {}, "Name is required");
        } else if (form.getName().length() > CustomerConstant.LENGTH_NAME) {
            errors.rejectValue("name", ValidatorConstant.KEY_MAX_LENGHT, 
            		new Object[] {CustomerConstant.LENGTH_NAME }, "Name is too long");
        }

	}

}
